<?php
namespace common\services;

use common\base\BaseActiveRecord;
use common\helpers\TStringHelper;
use common\models\FrontendMenu;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;

class FrontendMenuServices extends FrontendMenu
{

    /**
     * 获取页面导航
     * @param $page
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getMenu($position = null){
        $cacheKey = 'menu_'.$position;
        $cache = \Yii::$app->cache;
        $res = $cache->get($cacheKey);
        if ($res === false) {
            $model = FrontendMenu::find(false);
            $model->andFilterWhere(['=', 'position', $position])
                ->andFilterWhere(['=', 'status', self::STATUS_FLAG_NORMAL])
                ->orderBy('order desc,id asc')
                ->select('id,name,parent_id,position,code,url,icon,is_single,params')->indexBy('id')
                ->asArray();

            $res = $model->all();
            $cache->set($cacheKey, $res);
        }

        return $res;

    }

    /**
     * @param null $parentId
     * @return ActiveDataProvider
     */
    public function getList($parentId = null, $pageSize = 15){
        $model = FrontendMenu::find(false);
        $key = TStringHelper::getFrontendMenuPosition();
        $value = array_keys($key);
        if (!empty($parentId) && is_numeric($parentId)) {
            $model->andFilterWhere(['=', 'parent_id', $parentId]);
        }elseif (in_array($parentId, $value)){
            $model->andFilterWhere(['=', 'position', $parentId]);
        }
        $model->addOrderBy('order desc');
        $dataProvider = new ActiveDataProvider([
            'query' => $model,
            'pagination' => [
                'pagesize' => $pageSize,
            ]
        ]);
        return $dataProvider;
    }

    /**
     * 分类树
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getData($parentId = null){
        $model = FrontendMenu::find(false);
        $model->andFilterWhere(['=', 'status', BaseActiveRecord::STATUS_FLAG_NORMAL])
            ->addOrderBy([
                'id' => SORT_ASC,
                'order' => SORT_DESC
            ]);
        if (!empty($parentId)){
            $model->andFilterWhere(['=', 'parent_id', $parentId]);
        }

        $list = $model->select('id,name,parent_id,position')->asArray()->all();
        $result = array();
        if (!empty($list)){
            foreach ($list as $item){
                if ($item['parent_id'] == 0){
                    $result['parent'][] = $item;
                }else{
                    $result['children'][$item['parent_id']][] = $item;
                }
            }
        }
        return $result;
    }

    /**
     * 获取分类树
     * @param $data
     * @param bool $addBtn
     * @param bool $editBtn
     * @param bool $deleteBtn
     * @return string
     */
    public function getTree($data){
        $category_directory = \Yii::t('common', 'category_directory');
        $html = "<ul>";
        $html .= "<li class=\"jstree-open\" id='0' data-jstree='{\"opened\":true,\"selected\":true,\"icon\":\"glyphicon glyphicon-duplicate\"}'>$category_directory";
        if (!empty($data['parent'])){
            $positionArray = TStringHelper::getFrontendMenuPosition();
            $html .= "<ul>";
            foreach ($positionArray as $k => $val) {
                $html .= "<li id=\"" . $k . "\" data-jstree='{\"icon\":\"glyphicon glyphicon-duplicate\"}'>" . $val;
                $html .= "<ul>";
                foreach ($data['parent'] as $item) {
                    if ($item['position'] == $k) {
                        $html .= "<li id=\"" . $item['id'] . "\" data-jstree='{\"icon\":\"glyphicon glyphicon-duplicate\"}'>" . $item['name'];
                        if (!empty($data['children'][$item['id']])) {
                            $html .= "<ul>";
                            foreach ($data['children'][$item['id']] as $v) {
                                $html .= "<li id=\"" . $v['id'] . "\" data-jstree='{\"icon\":\"glyphicon glyphicon-duplicate\"}'>" . $v['name'];
                                if (!empty($data['children'][$v['id']])) {
                                    $html .= "<ul>";
                                    foreach ($data['children'][$v['id']] as $vv) {
                                        $html .= "<li id=\"" . $vv['id'] . "\" data-jstree='{\"icon\":\"glyphicon glyphicon-duplicate\"}'>" . $vv['name'] . "</li>";
                                    }
                                    $html .= "</ul>";
                                }
                                $html .= "</li>";
                            }
                            $html .= "</ul>";
                        }
                        $html .= "</li>";
                    }
                }
                $html .= "</ul></li>";
            }
            $html .= "</ul>";
        }
        $html .= "</li>";
        $html .= "</ul>";
        return $html;
    }

    /**
     * @param $parentId
     * @return int|string
     */
    public function getChildCount($parentId = null){
        $model = FrontendMenu::find(false);
        if (!empty($parentId)) {
            $model->andFilterWhere(['=', 'parent_id', $parentId]);
        }

        return $model->count(1);
    }

    /**
     * 返回上级菜单
     * @param $code
     * @return mixed|null|static
     */
    public function getParentByCode($code){
        $model = FrontendMenu::findOne(['code' => $code, 'status' => FrontendMenu::STATUS_FLAG_NORMAL]);
        if (empty($model->parent_id)) return false;
        $parent = FrontendMenu::findOne($model->parent_id);
        if (empty($parent)) return false;
        $child = FrontendMenu::find()->andFilterWhere(['parent_id' => $model->parent_id])->asArray()->orderBy('order desc, id asc')->all();
        if (!empty($child)) {
            $singlePageService = new SinglePageService();
            foreach ($child as &$val) {
                $val['page'] = $singlePageService->getSinglePageByCode($val['code']);
            }
        }
        $data = array(
            'parent' => $parent,
            'child' => $child,
        );
        return $data;
    }

}
